package com.fiberhome.boot.demo.seaweedfs;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.fiberhome.boot.utils.SeaweedClient;
import com.fiberhome.boot.utils.SeaweedResponse;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping(value="file")
@Api(value = "上传下载", description="上传下载", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class SeaweedFsController implements CommandLineRunner{

	@Value("${SeaweedFs.host}")
	private String host;
	
	@Value("${SeaweedFs.port}")
    private Integer port;
	
	SeaweedClient client;
	
	@Override
	public void run(String... arg0) throws Exception {
		client = new SeaweedClient(host, port);
	}
	
	@ApiOperation(value="上传文件", notes="上传文件")
	@RequestMapping(value="/upload",method=RequestMethod.POST)
	public SeaweedResponse upload(@RequestParam("file")MultipartFile file){
		SeaweedResponse response = new SeaweedResponse();
		if(!file.isEmpty()){
			try {
				response = client.saveFile(file);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return response;
	}
	
	@ApiOperation(value="获取下载路径", notes="获取下载路径")
	@RequestMapping(value="/downloadUrl",method=RequestMethod.GET)
	public String downloadUrl(@RequestParam("fileId")String fileId){
		String url = "";
		try {
			url =  client.getFile(fileId);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return url;
	}
	@ApiOperation(value="批量上传文件", notes="批量上传文件")
	@RequestMapping(value="/batch/upload", method= RequestMethod.POST) 
    public List<SeaweedResponse> handleFileUpload(HttpServletRequest request){ 
		List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("file"); 
        List<SeaweedResponse> responses = new ArrayList<>();
        if(files.size()!=0){
        	for(MultipartFile temp : files){
        		try {
					SeaweedResponse response = client.saveFile(temp);
					responses.add(response);
				} catch (IOException e) {
					e.printStackTrace();
				}
        	}
        }
        return responses;
	}
}
